library(rkward)
library(GDD)

# Read input file
ocr.data <<- read.table (file="input/OCR.arff", header=FALSE, sep=',', quote='"\'', dec='.', fill=FALSE, comment.char="#", col.names = c("class", "x-box", "y-box", "width-box", "heigth-box", "npix", "x-var-pix", "y-var-pix", "x2bar", "y2bar", "xybar", "x2ybr", "xy2br", "x-ege", "xegvy", "y-ege", "yegvx"), na.strings = "NA", nrows = -1, skip = 59, check.names = TRUE, strip.white = FALSE, blank.lines.skip = TRUE)

# Select variable to be analized
vars <- list (substitute (ocr.data[["yegvx"]]), substitute (ocr.data[["y2bar"]]), substitute (ocr.data[["y.var.pix"]]), substitute (ocr.data[["y.ege"]]), substitute (ocr.data[["y.box"]]), substitute (ocr.data[["xybar"]]), substitute (ocr.data[["xy2br"]]), substitute (ocr.data[["xegvy"]]), substitute (ocr.data[["x2ybr"]]), substitute (ocr.data[["x2bar"]]), substitute (ocr.data[["x.var.pix"]]), substitute (ocr.data[["x.ege"]]), substitute (ocr.data[["x.box"]]), substitute (ocr.data[["width.box"]]), substitute (ocr.data[["npix"]]), substitute (ocr.data[["heigth.box"]]))

# Prepare result vector
results <- data.frame ('Variable Name'=rep (NA, length (vars)), check.names=FALSE)

for (i in 1:length (vars))  {
	var <- eval (vars[[i]], envir=globalenv());
	
	results[i, 'Variable Name'] <- rk.get.description(vars[[i]], is.substitute=TRUE)

    # Stats
	results[i, 'Number of obs'] <- length(var)
	results[i, 'Number of missing values'] <- sum(is.na(var))
	results[i, 'Mean'] <- mean(var,na.rm=TRUE)
	results[i, 'Variance'] <- var(var,na.rm=TRUE)
	results[i, 'Sd'] <- sd(var,na.rm=TRUE)
	results[i, 'Minimum'] <- min(var,na.rm=TRUE)
	results[i, 'Maximum'] <- max(var,na.rm=TRUE)
	if (length (var) >= 1) {
		results[i, 'Minimum values'] <- paste (sort(var, decreasing=FALSE, na.last=TRUE)[1:1], collapse=" ")
	}
	if (length (var) >= 1) {
		results[i, 'Maximum values'] <- paste (sort(var, decreasing=TRUE, na.last=TRUE)[1:1], collapse=" ")
	}
	results[i, 'Median'] <- median(var,na.rm=TRUE)
	results[i, 'Inter Quartile Range'] <- IQR(var,na.rm=TRUE)
	temp <- quantile (var,na.rm=TRUE)
	results[i, 'Quartiles'] <- paste (names (temp), temp, sep=": ", collapse=" ")
	
	# Histograms
	filename <- paste(i, results[i, 'Variable Name'], sep=".")
	plotname <- results[i, 'Variable Name']
    GDD(file=paste("output/Histogram.", filename, sep=""), type="png", w=800, h=600)
    hist(var, probability=TRUE, breaks=15, main=paste("Histogram for", plotname), xlab="Value")
    rug(var)
    dev.off()

}

# Save stats
write.table(results, file = "output/OCR-stats.csv", sep = ",", row.names = FALSE)



    

